//
//  CHDeviceViewController.swift
//  Checked
//
//  Created by admin on 07/03/2017.
//  Copyright © 2017 shinolr_go. All rights reserved.
//

import UIKit
import WebKit

private var code: String?
let days = 7

class CHOAuthViewController: UIViewController {
    var oAuthRequest: URLRequest {
        let oAuthString = "https://trakt.tv/oauth/authorize?client_id=" + clientID + "&redirect_uri=" + redirect_uri + "&response_type=" + "code"
        let oAuthUrl = URL(string: oAuthString)!
        return URLRequest(url: oAuthUrl)
    }

    var webView: WKWebView!

    private var code: String?

    override func loadView() {
        webView = WKWebView()
        webView.navigationDelegate = self
        view = webView
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        let leftPop = UIBarButtonItem(barButtonSystemItem: .cancel, target: self, action: #selector(popAction))
        navigationItem.leftBarButtonItem = leftPop
        webView.load(oAuthRequest)
        /// 请求用户授权
//        TraktProvider.request(.authorize) { (result) in
//            switch result {
//            case let .success(moyaResponse):
//                let data = moyaResponse.data
//                print(moyaResponse.request!)
//                self.webView.loadRequest(moyaResponse.request!)
//                break
//            case let .failure(error):
//                break
//            }
//        }
//        CHUserAccountViewModel.sharedUserAccount.requestAuthorize { [weak self] (request) in
//            self?.webView.loadRequest(request!)
//        }
    }

    @objc func popAction() {
        navigationController?.popViewController(animated: true)
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

extension CHOAuthViewController: WKNavigationDelegate {
    func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
        let url = navigationAction.request.url!
        if url.host == "oauth", url.scheme == "checkedapp", let query = url.query {
            code = String(query["code=".endIndex...])
            traktProvider.request(.accessToken(code: code!)) { (result) in
                switch result {
                case let .success(response):
                    print(String(bytes: response.data, encoding: .utf8)!)
                    let decoder = JSONDecoder()
                    do {
                        let model = try decoder.decode(AccessTokenModel.self, from: response.data)
                        model.saveAccessToken {
//                            self.dismiss(animated: true, completion: {
//                                self.navigationController?.dismiss(animated: true, completion: nil)
//                            })
                            self.navigationController?.popViewController(animated: true)
                        }
                        print(AccessTokenModel.currentAccessToken!)
                    } catch let error {
                        print(error)
                        // decode 失败
                    }
                default: break
                }
            }
        }
        decisionHandler(.allow)
    }
}
